
var util = require('../../utils/util.js')
var utilMd5 = require('../../utils/md5.js');
var base64 = require('../../utils/Base64.js');

const Upyun = require('../../utils/upyun-wxapp-sdk');
var app = getApp();
var reload = true;
var buy_hasMore = true;
var buy_loadingMore = false;
var sell_hasMore = true;
var sell_loadingMore = false;

var page = 1;
var tc = 0;
const upyun = new Upyun({
  bucket: util.upyun_bucket,
  operator: util.upyun_opterator,
  getSignatureUrl: util.upyun_getSignUrl
});
Page({

  /**
   * 页面的初始数据
   */
  data: {
    util: util,
    tc: 0,

    buy_orders: [],
    hasBuyData:true,
    sell_orders: [],
    hasSellData: true,
    uid:0,
    token:'',
    openid:'',
    canEdit: 0,
    roomList:[],
    roomselect:-1,
    showMoreAct:false,

    tabCataData: [{ id: 0, title: "未处理", subList: [] },
    { id: 1, title: "已处理", subList: [] }],

    uploadImg:[]
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var tc = app.get_tc();
    var titlename =  tc == 1 ? '簽到' : '签到';
    wx.setNavigationBarTitle({
      title: titlename,
    })
    wx.showLoading({
      title: '加载中',
      mask: 'true'
    })
    page = 1;
    var that = this;
    tc = app.get_tc();
    that.setData({
      tc: tc
    })
    if(tc == 1){
      titlename = '訂單';
    }
    var isAdmin=options.isAdmin||'';
    if(isAdmin){
      that.setData({
        isAdmin: isAdmin,
        actionList: [
          { status: 1, action: '已接单' },
          { status: 2, action: '已配送' },          
          { status: -1, action: '无法接单' },
          { status: -2, action: '已退款' },
        ]
      })
      if (util.orgid == 18535){
        that.setData({
          actionList: [
            { status: 1, action: '已接单' },
            { status: 2, action: '已分配房间' },
            { status: -1, action: '无法接单' },
            { status: -2, action: '已退款' },
          ]
        })
      }
    }
    console.log("isAdmin:", isAdmin)
    wx.setNavigationBarTitle({
      title: titlename,
    });

    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color
      })
      that.resetNavColor();
    });
    //初始化底部导航
    var b_nav_data = app.getBottomNavData('order-list/order-list', function (data) {
      that.setData({
        bottom_nav_data: data,
        nav_bgColor: data[0].bgcolor
      });
    });

    wx.getSystemInfo({
      success: function (res) {
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          isIphone_x: isIphone_x,
          screen_h: res.windowHeight,
        });
      }
    });
    reload = true;
    //当前登录用户信息
    app.LoginUserInfo(function (res) {
      var authFail = res == -1;//用户拒绝授权
      if (authFail) {
        wx.hideLoading();
        app.reAuthorize(that.reGetUserInfo);
        return;
      }
      //更新数据
      that.setData({
        uid: res.uid,
        token: res.token,
        openid: res.wxsmall_openid
      });
      if (that.data.isAdmin){
        that.adminGetZongOrderList(2, 1, 20, true);
      } else {
        that.getZongOrderList(2, 1, 20, true);

      }
      
    });

  },

  loadMore: function (e) {
    
    if (buy_hasMore && !buy_loadingMore) {
        buy_loadingMore = true;
        page++;
        this.getZongOrderList(2, page, 20, false);
        this.adminGetZongOrderList(2, page, 20, false);

      } else {
        console.log("没有更多了");
      }
    
  },


  //获取订单 列表  type: 1 卖出  2:买入
  // * page: 
  // refresh 是否是刷新
  getZongOrderList: function (orderType, page, num, refresh) {
    var that = this;
    var params = {
      "ac": "getzongorder",
      "publickey": util.publiccode,
      "type": orderType,
      "page": page,
      "num": num,
    };
    if (!num) {
      num = 20;
    }
    if (orderType == 2) {//买入
      params.uid = that.data.uid;
    }
    console.log("orders params:", params);
    util.api({
      data: params,
      success: function (responseData) {
        console.log(responseData);
        if (!responseData.data.msg) {
          console.log(responseData.data);
          //买入
          var result = responseData.data;
          if (!refresh && that.data.buy_orders.length > 0) {
            result = that.data.buy_orders.concat(responseData.data);
          }
          for(var i=0 ;i<result.length;i++){

            // result[i].cartinfoObj = JSON.parse(result[i].cartinfo)
            if(util.orgid==18535){
              var fendan=result[i].fendan;
              for (var j = 0; j < fendan.length; j++){
                fendan[j].time_end
              }
            }

          }
          console.log('result:',result)
          that.setData({
            buy_orders: result
          });
          // that.setData({
          //   hasBuyData: false
          // });

          // that.loadGoodsListData(0, 1)

        } else {
          //买入
          buy_hasMore = false;
          if (that.data.buy_orders.length <= 0) {
            that.setData({
              hasBuyData: false
            });
          }

          that.loadGoodsListData(0,1)

        }
        //买入
        buy_loadingMore = false;

        wx.hideLoading();
      }
    });
  },
  adminGetZongOrderList: function (orderType, page, num, refresh) {
    var that = this;
    var params = {
      "ac": "admingetzongorder",
      "publickey": util.publiccode,
      "type": orderType,
      "page": page,
      "num": num,
      "orgid":util.orgid
    };
    if (!num) {
      num = 20;
    }
    if (orderType == 2) {//买入
      params.uid = that.data.uid;
    }
    console.log("orders params:", params);
    util.api({
      data: params,
      success: function (responseData) {
        console.log(responseData);
        if (!responseData.data.msg) {
          console.log(responseData.data);
          //买入
          var result = responseData.data;
          if (!refresh && that.data.buy_orders.length > 0) {
            result = that.data.buy_orders.concat(responseData.data);
            if (that.data.isAdmin) {
              result = that.data.buy_orders_source.concat(responseData.data);
            }
          }
          console.log('result:',result)
          that.setData({
            buy_orders: result
          });
          if (that.data.isAdmin) {
            that.setData({
              buy_orders_source: result
            });
          }

        } else {
          //买入
          buy_hasMore = false;
          if (that.data.buy_orders.length <= 0) {
            that.setData({
              hasBuyData: false
            });
          }

        }
        //买入
        buy_loadingMore = false;

        wx.hideLoading();
      }
    });
  },

  //重新读取 登录用户信息
  reGetUserInfo: function (e) {
    var that = this;
    console.log("reGetUserInfo: ", e);
    if (e == 1) {
      // wx.reLaunch({ //用这个会报错fail can not invoke relaunch in background
      wx.redirectTo({
        url: '/pages/order-list/order-list'
      })
    } else {
      wx.redirectTo({
        url: '/pages/index/index'
      })
    }
  },

  recgoods:function() {
    console.log(123)
  },
  
  repayOldOrder: function(event){
    var that = this;
    var order = event.currentTarget.dataset.order;
    var orderid = order.out_trade_no;
    var privatekey = utilMd5.hexMD5(this.data.uid + 'zongoldpay' + this.data.token);
    that.setData({
      order: order
    })
    var data = {
      'ac': 'zongoldpay',
      'orderid': orderid,
      'binduid': util.orgid,
      'uid': this.data.uid,
      'privatekey': privatekey
    };

    // that.paytuisong()
    console.log("支付老订单参数：", data);
    util.api({
      data: data,
      method: 'POST',
      success: function (responseData) {
        var data = responseData.data;

        console.log("支付老订单返回：", data);
        if (data.res === true) {
            //挂起微信支付请求
            var orderData = data.data;
            wx.requestPayment({

              'timeStamp': orderData.timeStamp,
              'nonceStr': orderData.nonceStr,
              'package': orderData.package,
              'signType': orderData.signType,
              'paySign': orderData.paySign,
              'success': function (res) {
                app.dialog('支付成功', 'success', function () {
                  //刷新
                  var orders = that.data.buy_orders;
                  for (var i = 0; i < orders.length; i++) {
                    var itemJo = orders[i];
                    if (order.out_trade_no == itemJo.out_trade_no) {
                      orders[i].status = 1;
                        that.setData({
                          buy_orders: orders
                        });
                      break;
                    }
                  }
                  that.paytuisong()
                });
                if (parseInt(orderData.add_source) > 0){
                  var toice1 = tc == 1 ? '恭喜妳獲得' : '恭喜你获得';
                  var toice2 = tc == 1 ? '積分' : '积分';
                  var toice = toice1 + orderData.add_source + toice2;
                  wx.showModal({
                    title: '支付成功',
                    content: toice,
                    showCancel: false,
                    success: function (res) {
                      if (res.confirm) {

                      }
                    }
                  })
                }
              },
              'fail': function (res) {
                console.log(res);
                if (res.errMsg == 'requestPayment:fail cancel') {

                } else {
                  app.dialog(res.errMsg, 'loading');
                }
              }
            });
          
        } else {
          app.dialog('购买失败', 'loading');
        }
      }
    });
  },


  //取消订单
  cancelorder: function (event) {
    var that = this;
    var order = event.currentTarget.dataset.order;
    console.log(order);
    var privatekey = utilMd5.hexMD5(this.data.uid + 'cancelgoodsorder' + this.data.token);
    var data = {
      publickey: util.publiccode,
      ac: "cancelgoodsorder",
      reason: '默认取消',
      orderid: order.orderid,
      uid: this.data.uid,
      privatekey: privatekey
    };
    
    util.api({
      data: data,
      method: 'POST',
      success: function (responseData) {
        var data = responseData.data;
        console.log("取消订单：",data);
        if (data.res) {
          //刷新
          var orders = that.data.buy_orders;
          
          for(var i = 0; i < orders.length; i++){
            var itemJo = orders[i];
            if (order.orderid == itemJo.orderid){
              orders[i].status = -1;
              
                that.setData({
                  buy_orders: orders
                });
              
              break;
            }
          }
        } else {
          app.dialog(data.msg, 'loading');
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that=this;
    if(!reload){
      var buy_len = this.data.buy_orders.length;
      buy_len = buy_len > 0 ? buy_len : 20;
      if(that.data.isAdmin){
        this.adminGetZongOrderList(2, 1, buy_len, true);
      } else {
        this.getZongOrderList(2, 1, buy_len, true);

      }
    }
    reload = false;
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;    
    wx.navigateTo({ url: url })
  },
  goAtherPageRedirect: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.redirectTo({ url: url })
  },

  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    if (path) {
      wx.redirectTo({ url: path })
    }
  },
  resetNavColor: function () {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },
  updateAttr: function (event){
    console.log("updateAttr", event.currentTarget.dataset);
    var that = this;
    var orderid = that.data.fendan.orderid;
    var fendanid = that.data.fendan.fendanid;
    var topicid = that.data.fendan.goods.id;
    var roomid = event.currentTarget.dataset.roomid;

    // var addAttr={ groupId: "0", groupName: "房号", attributeId: "", attributeName: "888" }
    // var attribute = [];
    // attribute = event.currentTarget.dataset.attr || [];

    // for (var i = 0; i < attribute.length; i++) {
    //   if (attribute[i].groupName == "房号") {
    //     attribute.splice(i, 1);
    //     i--;
    //   }
    // }
    // attribute.push(addAttr);
    // console.log("attribute房号", attribute);
    var privatekey = utilMd5.hexMD5(this.data.uid + 'hotelupdateorder' + this.data.token);
    var data = {
      publickey: util.publiccode,
      ac: "hotelupdateorder",
      orderid: orderid,
      fendanid: fendanid,
      uid: this.data.uid,
      roomid: roomid,
      topicid: topicid,
      // goods_attribute: JSON.stringify(attribute),
      privatekey: privatekey
    };

    util.api({
      data: data,
      method: 'POST',
      success: function (responseData) {
        var data = responseData.data;
        console.log("更新订单：", data);
        if (data.res) {
          that.adminGetZongOrderList(2, 1, 20, true);
          that.hideModalAct()
        } else {
          app.dialog(data.msg, 'loading');
        }
      }
    });

  },
  getDistributionRoom:function(e){
    var that = this;
    // that.showModalAct();
    var fendan = e.currentTarget.dataset.fendan;
    that.setData({
      fendan: fendan
    })
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "getDistributionRoom",
        "uid": that.data.uid,
        "orgid":util.orgid,
        "timeStart": fendan.time_start,
        "timeEnd": fendan.time_end,
        "buildingid": fendan.maiuid,
        "topicid": fendan.goods.id
      },
      success: function (responseData) {
        console.log(responseData);
        var data = responseData.data;
        console.log("roomList", data);
        if (data && data.length > 0) {
          that.setData({
            hasData: true,
            roomList: data,
          });
          console.log("roomList",data);

          that.showModalAct();
        }else{
          if(data.msg=="日期已过"){
            wx.showModal({
              title: '提示',
              content: '日期已过',
            })
          } else {
            that.setData({
              hasData: false,
              roomList: [],
            });
            wx.showModal({
              title: '提示',
              content: '无房可分配',
            })

          }
        }
      }
    });
  },

  showModalAct: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showMoreAct: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showMoreAct: true
      })
    }.bind(this), 200)
  },
  hideModalAct: function () {
    var that = this;
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showMoreAct: false
      })
    }.bind(this), 200);
  },

  changeTabCata: function (e) {
    console.log("Tabcurrcata", e.currentTarget.dataset.current)
    var cur = e.currentTarget.dataset.current;
    if (this.data.tabcurrcata == cur) { 
      return false; 
    } else {
      this.setData({
        tabcurrcata: cur
      })
      var that = this;
      that.data.tabCataData[that.data.tabcurrcata].subList = [];
    }
    
    
    var buy_orders_source = [].concat(that.data.buy_orders_source);
    var buy_orders = that.data.buy_orders_source;
    for (var i = 0; i < buy_orders.length;i++){
      if (this.data.tabcurrcata == 0) {
        if (buy_orders[i].fendan[0].roomid) {
          buy_orders.splice(i, 1);
          i--
        }
      } else if (this.data.tabcurrcata == 1) {
        if (!buy_orders[i].fendan[0].roomid) {
          buy_orders.splice(i, 1);
          i--
        }
      }
    }
    this.setData({
      buy_orders_source: buy_orders_source,
      buy_orders: buy_orders
    })  

  },
  loadGoodsListData: function (zhiding, jingxuan) {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "topiclist",
      topictype: '4',
      tc: that.data.tc,
      orgid: util.orgid,
      zhiding: zhiding,
      shopgoodscata: jingxuan,
      page: 1,
      num: 4
    };

    // console.log("商品请求参数：", params);
    util.api({
      data: params,
      success: function (responseData) {
        console.log("zhiding:" + zhiding + "; shopgoodscata:" + jingxuan);
        console.log("商店商品数据:", responseData);
        var resData = responseData.data;
        if (!resData.msg) {
          if (zhiding == 1) {//热销推荐
            that.setData({
              tuijianData: resData
            })
          } else if (jingxuan == 1) {//精选
            that.setData({
              djJingxuanData: resData
            })

            console.log("精选===>>>:", resData);
          } else { //新品上市
            that.setData({
              xinpin_data: resData
            })
          }
        }

        // wx.hideLoading();
      }
    });
  },
  bindStatusPickerChange:function(e){
    console.log(e);
    var that=this;
    var status=that.data.actionList[e.detail.value].status;
    var action=that.data.actionList[e.detail.value].action;
    var order=e.currentTarget.dataset.order;
    var orderid=e.currentTarget.dataset.order.id;
    console.log("status", status);
    console.log("updateOrderStatus");
    
    var g_info = '';
    for (var i = 0; i < order.fendan.length; i++) {
      var goodsItem = order.fendan[i];
      g_info = g_info + goodsItem.goods_name + '  ' + goodsItem.count + ' 瓶；' + '  ';
    }
    var privatekey = utilMd5.hexMD5(this.data.uid + 'updateorderstatus' + this.data.token);
    var data = {
      publickey: util.publiccode,
      ac: "updateorderstatus",
      privatekey: privatekey,
      orderid: orderid,
      out_trade_no:order.out_trade_no,
      uid: that.data.uid,
      touid: order.uid,
      name: order.fendan[0].consignee,
      phone: order.fendan[0].phone,
      addr: order.fendan[0].addr,
      status: status,
      action: action,
      goods_list: g_info,
      btime: order.addtimefm,
      booktime:order.booktime
    };

    util.api({
      data: data,
      method: 'POST',
      success: function (responseData) {
        var data = responseData.data;
        console.log("更新订单状态：", data);
        if (data.res) {
          that.adminGetZongOrderList(2, 1, 20, true);

        } else {
          app.dialog(data.msg, 'loading');
        }
      }
    });

  },
  enterRoom:function(e){
    console.log(e);
    var that=this;
    var status=3;
    var action='立即租住';
    var order=e.currentTarget.dataset.order;
    var orderid = e.currentTarget.dataset.order.id;
    var fendan = e.currentTarget.dataset.fendan;
    var fendanid = e.currentTarget.dataset.fendan.id;
    var roomNumber = e.currentTarget.dataset.fendan.roominfo.number;
    console.log("status", status);
    console.log("enterRoom");
    var privatekey = utilMd5.hexMD5(this.data.uid + 'enterroom' + this.data.token);
    var data = {
      publickey: util.publiccode,
      ac: "enterroom",
      privatekey: privatekey,
      orgid: util.orgid,
      orderid: orderid,
      fendanid: fendanid,
      out_trade_no:order.out_trade_no,
      uid: that.data.uid,
      status: status,
      action: action,
      uname: fendan.consignee,
      phone: fendan.phone,
      roomnumber: roomNumber
    };

    util.api({
      data: data,
      method: 'POST',
      success: function (responseData) {
        var data = responseData.data;
        console.log("更新订单状态：", data);
        if (data.res) {
          that.getZongOrderList(2, 1, 20, true);

        } else {
          app.dialog(data.msg, 'loading');
        }
      }
    });

  },

  checkout:function(e){
    console.log(e);
    var that=this;
    var status=3;
    var action='客人退房';
    var order=e.currentTarget.dataset.order;
    var orderid=e.currentTarget.dataset.order.id;
    var fendan = e.currentTarget.dataset.fendan;
    var roomNumber = e.currentTarget.dataset.fendan.roominfo.number;
    console.log("status", status);
    console.log("checkout");
    var privatekey = utilMd5.hexMD5(this.data.uid + 'checkout' + this.data.token);
    var data = {
      publickey: util.publiccode,
      ac: "checkout",
      privatekey: privatekey,
      orgid: util.orgid,
      orderid: orderid,
      fendanid: fendan.fendanid,
      out_trade_no:order.out_trade_no,
      uid: that.data.uid,
      uname:fendan.consignee,
      phone: fendan.phone,
      roomnumber: roomNumber
    };

    util.api({
      data: data,
      method: 'POST',
      success: function (responseData) {
        var data = responseData.data;
        console.log("退房：", data);
        if (data.res) {
          wx.showModal({
            title: '你的要求已发送，请等待回复',
            content: '',
          })

        }
      }
    });

  },

  //支付订单推送
  paytuisong: function (e) {
    console.log(e);
    var that = this;
    var order = that.data.order;
    console.log("paytuisong");

    var g_info = '';
    for (var i = 0; i < order.fendan.length; i++) {
      var goodsItem = order.fendan[i];
      g_info = g_info + goodsItem.goods_name + '  ' + goodsItem.count + ' 瓶；' + '  ';
    }

    var tmpmd5 = utilMd5.hexMD5(that.data.uid + "paytuisong" + that.data.token);
    var data = {
      "privatekey": tmpmd5,
      "ac": "paytuisong",
      "uid": that.data.uid,
      // "cartinfo": JSON.stringify(cartinfoArr),
      "binduid": util.orgid,
      "total_fee": order.total_fee/100,
      "name": order.fendan[0].consignee,
      "phone": order.fendan[0].phone,
      "address": order.fendan[0].addr,
      'out_trade_no': order.out_trade_no,
      'booktime': order.booktime,
      "btime": that.toDate(order.ctime),
      'goods_list': g_info,
    };

    util.api({
      data: data,
      method: "POST",
      success: function (responseData) {
        console.log("paytuisong===", responseData);
      }
    });
  }, 
  //时间戳转换时间  
  toDate: function (number) {
    var n = number * 1000;
    var date = new Date(n);
    var Y = date.getFullYear() + '.';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '.';
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var H = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
    var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    console.log(Y + M + D + "  " + H + ':' + m)
    return (Y + M + D + "  " + H + ':' + m)

  },
  

  uploadImgs: function (e) {
    var that = this;
    that.setData({
      roomid:e.currentTarget.dataset.roomid
    })
    var photos = this.data.uploadImg;

    if (photos.length >= 9) {
      app.dialog('最多上传9张图片', 'loading');
      return false;
    }

    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        wx.showLoading({ title: '图片上传中..', mask: 'true' });
        const tempFilePaths = res.tempFilePaths;
        const tempFileCount = tempFilePaths.length;
        var uploadCount = 0;
        that.setData({
          uploadImg: tempFilePaths.concat(photos)
        })
        for (var photoi = 0; photoi < tempFileCount; photoi++) {
          var imageSrc = res.tempFilePaths[photoi]
          var nowd = new Date();
          var nowm = nowd.getMonth() + 1;
          nowm = nowm.toString();
          if (parseInt(nowm) < 10) {
            nowm = '0' + nowm;
          }
          var nowda = nowd.getDate();
          nowda = nowda.toString();
          if (parseInt(nowda) < 10) {
            nowda = '0' + nowda;
          }
          var nowhour = nowd.getHours();
          nowhour = nowhour.toString();
          if (parseInt(nowhour) < 10) {
            nowhour = '0' + nowhour;
          }
          var imgUrl = '/' + nowd.getFullYear().toString() + '/' + (nowm + nowda) + '/' + nowhour + '/' + imageSrc.split('_')[1]
          upyun.upload({
            localPath: imageSrc,
            remotePath: imgUrl,
            success: function (res) {
              uploadCount++;
              if (uploadCount == tempFileCount) {
                wx.showToast({
                  title: '上传成功',
                  icon: 'success',
                  duration: 1000
                })
                that.uploadQRCode();
              }
              
            },
            fail: function ({ errMsg }) {
              uploadCount++;
              if (uploadCount == tempFileCount) {
                wx.showToast({
                  title: '上传成功',
                  icon: 'success',
                  duration: 1000
                })
              }
              console.log('uploadImage fail, errMsg is', errMsg)
            }
          })
        }
        //wx.hideLoading();
      },
      fail: function ({ errMsg }) {
        console.log('chooseImage fail, err is', errMsg)
      }
    });
  },
  uploadQRCode:function(){
    var that=this;
    if (!that.data.isAdmin) {
      return
    }
    var photos=that.data.uploadImg;
    var nowd = new Date();
    var nowm = nowd.getMonth() + 1;
    nowm = nowm.toString();
    if (parseInt(nowm) < 10) {
      nowm = '0' + nowm;
    }
    var nowda = nowd.getDate();
    nowda = nowda.toString();
    if (parseInt(nowda) < 10) {
      nowda = '0' + nowda;
    }
    var nowhour = nowd.getHours();
    nowhour = nowhour.toString();
    if (parseInt(nowhour) < 10) {
      nowhour = '0' + nowhour;
    }
    

    var photos_param = photos.map(function (item) { return item.replace('wxfile://tmp_', util.upyun_imgHost + '/' + nowd.getFullYear().toString() + '/' + (nowm + nowda) + '/' + nowhour + '/') }).join(',');

    var privatekey = utilMd5.hexMD5(this.data.uid + 'updateroomqrcode' + this.data.token);
    var params = {
      publickey: util.publiccode,
      ac: "updateroomqrcode",
      uid: that.data.uid,
      privatekey: privatekey,
      roomid:that.data.roomid,
      qrcode: photos_param,

    };
    util.api({
      data: params,
      method: "POST",
      success: function (responseData) {
        console.log(responseData);
        if (responseData.data.res) {
          wx.showToast({
            title: '成功上传二维码',
          })
          that.setData({
            uploadImg: []
          })
          that.adminGetZongOrderList(2, 1, 20, true);
        } else {
          wx.showToast({
            title: responseData.data.msg,
          })
        }
      }
    });
  },
  //点击图片放大
  showEWM: function (e) {
    var shareImgUrl = e.currentTarget.dataset.imgsrc;
    console.log("showEWM", shareImgUrl)
    if (!shareImgUrl) {
      return
    }
    wx.previewImage({
      current: shareImgUrl,
      urls: [shareImgUrl]
    })
  },


  signInOnclick:function(){
    app.dialog('處理中請再次到訪！', 'loading');
    
  },


  reNewOldOrder: function (event) {
    var that = this;
    var order = event.currentTarget.dataset.order;
    var orderid = order.out_trade_no;
    var privatekey = utilMd5.hexMD5(this.data.uid + 'zongoldpayrenew2' + this.data.token);
    that.setData({
      order: order
    })
    var c_obj = new Date()
    var a = c_obj.getFullYear() + '/' + c_obj.getMonth() + '/' + (c_obj.getDate()+1)   
    var dateEndObj = new Date(a);
    console.log("dateEndObj", dateEndObj, "||", dateEndObj.getTime())
    var data = {
      'ac': 'zongoldpayrenew2',
      'orderid': orderid,
      'binduid': util.orgid,
      'uid': this.data.uid,
      'privatekey': privatekey,
      'time_end': dateEndObj.getTime() / 1000 || ''
    };

    // that.paytuisong()
    console.log("续租订单参数：", data);
    util.api({
      data: data,
      method: 'POST',
      success: function (responseData) {
        var data = responseData.data;

        console.log("支付老订单返回：", data);
        if (data.res === true) {
          //挂起微信支付请求
          var orderData = data.data;
          wx.requestPayment({

            'timeStamp': orderData.timeStamp,
            'nonceStr': orderData.nonceStr,
            'package': orderData.package,
            'signType': orderData.signType,
            'paySign': orderData.paySign,
            'success': function (res) {
              app.dialog('支付成功', 'success', function () {
                //刷新
                var orders = that.data.buy_orders;
                for (var i = 0; i < orders.length; i++) {
                  var itemJo = orders[i];
                  if (order.out_trade_no == itemJo.out_trade_no) {
                    orders[i].status = 1;
                    that.setData({
                      buy_orders: orders
                    });
                    break;
                  }
                }
                that.paytuisong()
              });
              if (parseInt(orderData.add_source) > 0) {
                var toice1 = tc == 1 ? '恭喜妳獲得' : '恭喜你获得';
                var toice2 = tc == 1 ? '積分' : '积分';
                var toice = toice1 + orderData.add_source + toice2;
                wx.showModal({
                  title: '支付成功',
                  content: toice,
                  showCancel: false,
                  success: function (res) {
                    if (res.confirm) {

                    }
                  }
                })
              }
            },
            'fail': function (res) {
              console.log(res);
              if (res.errMsg == 'requestPayment:fail cancel') {

              } else {
                app.dialog(res.errMsg, 'loading');
              }
            }
          });

        } else {
          app.dialog('购买失败', 'loading');
        }
      }
    });
  },
})